<script setup lang="ts">
import Player from 'xgplayer'
import { ref, unref, onMounted, watch, onBeforeUnmount, nextTick } from 'vue'
import FlvPlugin from 'xgplayer-flv'
import 'xgplayer/dist/index.min.css'

const props = defineProps({
  url: {
    type: String,
    default: '',
    required: true
  },
  poster: {
    type: String,
    default: ''
  }
  // mediaType: {
  //   type: String,
  //   default: ''
  // },
  // playsinline: {
  //   type: Boolean,
  //   default: true
  // }
})

const playerRef = ref<Player>()

const videoEl = ref<HTMLDivElement>()
const intiPlayer = () => {
  if (!unref(videoEl)) return
  console.log('FlvPlugin.isSupported()', FlvPlugin.isSupported())
  new Player({
    autoplay: true,
    autoplayMuted: true,
    isLive: false,
    videoInit: true,
    // plugins: [FlvPlugin],
    // flv: {
    //   retryCount: 3, // 重试 3 次，默认值
    //   retryDelay: 1000, // 每次重试间隔 1 秒，默认值
    //   loadTimeout: 10000, // 请求超时时间为 10 秒，默认值
    //   fetchOptions: {
    //     // 该参数会透传给 fetch，默认值为 undefined
    //     mode: 'cors'
    //   }
    // },
    ...props,
    el: unref(videoEl)
  })
}

onMounted(() => {
  intiPlayer()
})

watch(
  () => props,
  async (newProps) => {
    await nextTick()
    if (newProps) {
      unref(playerRef)?.setConfig(newProps)
    }
  },
  {
    deep: true
  }
)

onBeforeUnmount(() => {
  unref(playerRef)?.destroy()
})

defineExpose({
  playerExpose: () => unref(playerRef)
})
</script>

<template>
  <div ref="videoEl"></div>
</template>
